interface QueryParam {
  domain: string
  callback: (...args: any[]) => void
  query: { [x: string]: string }
}

import { query2str } from '@/utils/tool'

export default function useJsonp({ domain, callback, query }: QueryParam, encodeFields: string[] = []) {
  const fnTag = `___${callback.name}___`
  const queryStr = query2str({ callback: fnTag, ...query }, encodeFields)
  const url = `${domain}?${queryStr}`

  const script = document.createElement('script')
  script.type = 'text/javascript'
  script.src = url
  // script.crossOrigin = 'anonymous'

  document.head.appendChild(script)

  window[fnTag] = (response: unknown) => {
    callback && callback(response)

    document.head.removeChild(script)

    delete window[fnTag]
  }
}
